package copyengine.resource.resProxy.cacheData
{
    import copyengine.log.CELog;
    import copyengine.utils.GeneralUtils;

    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.system.System;

    public class CEXMLResCacheData extends CEResCacheDataBasic
    {

        private var mURLLoader:URLLoader;
        private var mXML:XML;

        public function CEXMLResCacheData() {
            super();
        }

        override protected function doLoadRes():void {
            mURLLoader = new URLLoader();
            mURLLoader.dataFormat = URLLoaderDataFormat.BINARY;
            addListener();
            mURLLoader.load(new URLRequest(mFileDesc.filePath));
        }

        override public function getData():* {return mXML;}


        override protected function dispose():void {
            if (mLoadStatus == LOAD_STATUS_LOADED) {
                System.disposeXML(mXML);
                CELog.log("XML of : " + mFileDesc.fileName + " has been disposed");
            } else {
                removeListener();
                CELog.err("Can not release xml data as the file : " + mFileDesc.fileName + " not been loaded yet");
            }
            super.dispose();
        }

        private function addListener():void {
            GeneralUtils.addTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.addTargetEventListener(mURLLoader, ProgressEvent.PROGRESS, onLoadInProgress);
            GeneralUtils.addTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function removeListener():void {
            GeneralUtils.removeTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.removeTargetEventListener(mURLLoader, ProgressEvent.PROGRESS, onLoadInProgress);
            GeneralUtils.removeTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function onLoaded(e:Event):void {
            mXML = new XML(mURLLoader.data);
            removeListener();
            onResLoadComplete();
            //Loader资源可以释放掉
            mURLLoader = null;
        }

        private function onLoadInProgress(e:ProgressEvent):void {}

        private function onLoadInError(e:IOErrorEvent):void {
            removeListener();
            CELog.err(e.toString());
            CELog.err("CEXMLResCacheData-> load file in error, file: " + mFileDesc.toString());
        }
    }
}
